package com.bkhc.file.utils;

import com.bkhc.file.entity.FileBean;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtil {
    public static void downZipFile(List<FileBean> list) {
        //获得系统桌面路径
        //FileSystemView fsv = FileSystemView.getFileSystemView();
        //File home = fsv.getHomeDirectory();
        //String savePath = home.getPath();
        String savePath = "D:\\download_files";
        // 创建不同的文件夹目录
        File downloadFile = new File(savePath);
        // 判断文件夹是否存在
        if (!downloadFile.exists()) {
            // 如果文件夹不存在，则创建新的的文件夹
            downloadFile.mkdirs();
            downloadFile.setWritable(true);
        }
        //压缩包：路径+随机数+_download
        String zipName = savePath + "\\" + Math.random() + "_download.zip";
        File zipFile = new File(zipName);
        try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
             WritableByteChannel writableByteChannel = Channels.newChannel(zipOut)) {
            zipOut.setMethod(ZipOutputStream.DEFLATED);
            //遍历循环文件
            for (FileBean fileBean : list) {
                File file = new File(fileBean.getFilePath());
                try (FileChannel fileChannel = new FileInputStream(file).getChannel()) {
                    zipOut.putNextEntry(new ZipEntry(fileBean.getFileId().toString()));
                    fileChannel.transferTo(0, file.length(), writableByteChannel);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
